﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Common.Logging;
using InfoboardAdapterC.Common;
using InfoboardAdapterC.Parameter;
using InfoboardAdapterC.Properties;
using NKnife.IoC;
using RestSharp;

namespace InfoboardAdapterC.RestOperation
{
    public class InfoViewRestMessage
    {
        private static readonly ILog _loggerLog = LogManager.GetLogger<ParameterConfigView>();
        private readonly ParameterConfigViewModel _ParameterConfigView = DI.Get<ParameterConfigViewModel>();
        private readonly ParamentConfig _ParameterConfig = DI.Get<ParamentConfig>();
        private readonly SqlServerDal _ServerDb = DI.Get<SqlServerDal>();
        private readonly BoardInfoValueDataTable _BoardInfoValueDataTable = DI.Get<BoardInfoValueDataTable>();
        private string _SqlConnection;

        public InfoViewRestMessage()
        {
            InitParamenet();
        }

        public void InitParamenet()
        {
            _ParameterConfig.LoadConnectio(out string connection);
            _SqlConnection = connection;
        }

        /// <summary>
        /// 读取条目,处理并返回结果
        /// </summary>
        public void RunInfoViewRest()
        {
            var enterLibrary = GetBoardInfoEntry();
            var resultLibrary = GetArrayBoardInfoItems(enterLibrary);
            _BoardInfoValueDataTable.UpdateCache(resultLibrary,enterLibrary);//更新缓存
            SetBoardInfoEntry(resultLibrary);
        }
        /// <summary>
        /// 根据护士站获取发送信息表格
        /// </summary>
        /// <param name="hid"></param>
        public DataTable GetSendValueTable(string hid)
        {
            return _BoardInfoValueDataTable.GetTableByHid(hid);
        }

        private List<BoardItemsVM> GetArrayBoardInfoItems(List<BoardInfoLibrary> enterLibrary)
        {
            var hidList = LoadAreaId();
            var result = new List<BoardItemsVM>();
            foreach (var hid in hidList)
            {
                var hidArray = new List<BoardInfoItem>();
                hidArray.AddRange(from item in enterLibrary
                    where item.ItemType == "auto"
                    select new BoardInfoItem
                    {
                        itemId = item.ItemId,
                        buildingAreaId = hid,
                        itemData = LoaditemData(item.ItemInfo, hid)
                    });
                result.Add(new BoardItemsVM(hid, hidArray));
            }
            return result;
        }

        
        #region 数据库脚本操作

        private string LoaditemData(string itemInfo,string hid)
        {
            try
            {
             
                if (!string.IsNullOrEmpty(_SqlConnection))
                {
                    if (string.IsNullOrEmpty(itemInfo))
                        return "";
                    itemInfo = itemInfo.Replace("[wardid]", hid);
                    var resultList = _ServerDb.GetResult(itemInfo, _SqlConnection);
                    return string.Join(",", resultList.ToArray()); 
                }
                _loggerLog.Error("InfoViewRestMessage.LoadAreaId.sqlConnection:数据库连接字符串不能为空");
            }
            catch (Exception e)
            {
                _loggerLog.Error($"e.Message;语句:{itemInfo}");
            }
            return "";
        }

        private IEnumerable<string> LoadAreaId()
        {
            try
            {
                if (!string.IsNullOrEmpty(_SqlConnection))
                {
                    var resultList = _ServerDb.GetResult(Settings.Default.selectHid, _SqlConnection);
                    return resultList;
                }
                _loggerLog.Error("InfoViewRestMessage.LoadAreaId.sqlConnection:数据库连接字符串不能为空");
            }
            catch (Exception e)
            {
                _loggerLog.Error(e.Message);
            }
            return new List<string>();
        }


        #endregion


        private void PrintLoadRest(IEnumerable<BoardInfoLibrary> enterLibrary)
        {
            foreach (var item in enterLibrary)
            {
                _loggerLog.Info($"条目id{item.Id}条目编号{item.ItemId}条目名称{item.ItemName}条目内容{item.ItemInfo}");
            }
        }
        private void PrintSetRest(IEnumerable<BoardInfoItem> enterLibrary)
        {
            foreach (var item in enterLibrary)
            {
                _loggerLog.Info($"病区编号{item.buildingAreaId}条目编号{item.itemId}条目内容{item.itemData}");
            }
        }
        private void SetBoardInfoEntry(List<BoardItemsVM> boardInfoItems)
        {
            try
            {
                if (boardInfoItems == null)
                    return;
                var client = new RestClient(GetServerUrl());
                var request = new RestRequest("/birdnest/api/board/items", Method.PUT);
                request.AddHeader("authorization", "swagger2");
                request.AddJsonBody(boardInfoItems);
                _loggerLog.Info($"json:{boardInfoItems}");
                var response = client.Execute(request);
                var content = response.Content; // raw content as string 
                _loggerLog.Info($"收到：{content}");
            }
            catch (Exception e)
            {
                _loggerLog.Error($"InfoViewRestMessage.SetBoardInfoEntry{e.Message}");
            }
          
          
        }

        private List<BoardInfoLibrary> GetBoardInfoEntry()
        {
            try
            {
                var client = new RestClient(GetServerUrl());
                var request = new RestRequest("/birdnest/api/board/library/all", Method.GET);
                request.AddHeader("authorization", "swagger2");
                // execute the request 
                var response =
                    (RestResponse<BaseResultVo<List<BoardInfoLibrary>>>)client.Execute<BaseResultVo<List<BoardInfoLibrary>>>(request);
                return response.Data.Data;
            }
            catch (Exception ex)
            {
                _loggerLog.Warn($"InfoViewRestMessage.GetBoardInfoEntry获取条目语句异常, {0}", ex);
                return new List<BoardInfoLibrary>();
            }
        }
        private  string GetServerUrl()
        {
            _ParameterConfigView.LoadConfig(out string serviceIp, out string servicePort);
            if (serviceIp.Length == 0)
                serviceIp = "127.0.0.1";
            if (servicePort.Length == 0)
                servicePort = "7000";
            return $"http://{serviceIp}:{servicePort}";


        }
    }
}
